package com.seecen.controller;

import com.seecen.utils.CaptchaUtil;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;

/**
 * FIND YOUR PURPOSE
 *
 * @author: CYZ
 * @date: 2025/10/20/18:44
 * @description:
 */
@Slf4j
@RestController
@RequestMapping("/api")
public class CaptchaController {

    /**
     * 生成验证码图片
     * @param session HTTP会话，用于存储正确的验证码
     * @param response HTTP响应，用于输出图片
     * @throws IOException IO异常
     */
    @GetMapping("/captcha")
    public void getCaptcha(HttpSession session, HttpServletResponse response) throws IOException {
        // 生成验证码
        String captcha = CaptchaUtil.generateCaptcha(4);
        log.info("生成验证码: {}", captcha);

        // 将验证码存入session
        session.setAttribute("captcha", captcha);

        // 设置响应头
        response.setContentType("image/png");
        response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
        response.setHeader("Pragma", "no-cache");
        response.setDateHeader("Expires", 0);

        // 生成验证码图片并输出到响应
        CaptchaUtil.generateCaptchaImage(captcha, response.getOutputStream());
    }
}